Price Demand Analysis on Retail Data

Understanding sales pattern and measuring impact of price change on demand
Code
# Import Libraries
from nbdev.showdoc import *
import pandas as pd
import numpy as np
import plotly.express as px
import seaborn as sns
import statsmodels.api as sm
import statsmodels.formula.api as smf
from statsmodels.tsa.seasonal import seasonal_decompose
import matplotlib.pyplot as plt
import plotly.io as pio
pio.renderers.default='notebook'
from IPython.display import display_html 
import warnings
warnings.filterwarnings('ignore')
Code
# !pip install Jinja2
Code
# Load Dataset
df=pd.read_csv('Supermart_Dataset.csv')
Code
df.head()
Order ID Customer Name Customer Id Age Gender Category Sub Category Region State City Order Date Time Payment Method Sales Quantity Discount Profit Rating
0 OD1 Harish 13 53 Male Oil & Masala Masalas North Tamil Nadu Vellore 2017-11-08 13:03:25 Cash 1254 7 0.12 401.28 8.0
1 OD2 Sudha 38 31 Female Beverages Health Drinks South Tamil Nadu Krishnagiri 2017-11-08 12:09:46 Cash 749 14 0.18 149.80 1.0
2 OD3 Hussain 15 18 Male Food Grains Atta & Flour West Tamil Nadu Perambalur 2017-06-12 14:14:10 Credit card 2360 22 0.21 165.20 1.0
3 OD4 Jackson 16 69 Male Fruits & Veggies Fresh Vegetables South Tamil Nadu Dharmapuri 2016-10-11 09:22:01 Cash 896 13 0.25 89.60 8.0
4 OD5 Ridhesh 29 12 Male Food Grains Organic Staples South Tamil Nadu Ooty 2016-10-11 17:01:25 Ewallet 2355 8 0.26 918.45 9.0

Derive Price from Sales and Quantity: \(Price=Sales/Quantity\)

Code
df['Price']=df['Sales']/df['Quantity']
Code
# Convert date column to datetime format
df['Order Date']=pd.to_datetime(df['Order Date'])

Add Week, Month, Year and YearMonth to dataframe

Code
# Add week, month, year and yearmonth column
df['Week']=df['Order Date'].dt.isocalendar().week
df['Month']=df['Order Date'].dt.month
df['Year']=df['Order Date'].dt.isocalendar().year
df['YearMonth']=df['Order Date'].dt.strftime('%Y-%m')

Sales Pattern Analysis

Overall Level

There is yearly seasonal pattern observed and upward trend

Code
total_ym=df.groupby(['YearMonth'])['Sales'].agg(sum).reset_index()
fig = px.line(total_ym, x='YearMonth', y="Sales", markers=True)
fig.update_layout(title_text='Total Sales vs Year Month', title_x=0.5)
fig.show()
Code
total_q_ym=df.groupby(['YearMonth'])['Quantity'].agg(sum).reset_index()
fig = px.line(total_q_ym, x='YearMonth', y="Quantity", markers=True)
fig.update_layout(title_text='Total Quantitiy Sales vs Year Month', title_x=0.5)
fig.show()

Time Series Decomposition

Time series data has 3 components, trend, seasonal and residual

Trend Component: There is upward trend present in the data

Code
total_q_ym_sd=total_q_ym
total_q_ym_sd['YearMonth'] = pd.to_datetime(total_q_ym_sd['YearMonth'], format='%Y-%m')
total_q_ym_sd = total_q_ym_sd.set_index('YearMonth')
decompose = seasonal_decompose(total_q_ym_sd.Quantity).trend.plot()
decompose.figure.set_size_inches(15, 2)

Seasonal Component: There is yearly seasonality present in the data

Code
decompose = seasonal_decompose(total_q_ym_sd.Quantity).seasonal.plot()
decompose.figure.set_size_inches(15, 2)

There is no pattern observed between Price and Quantity at overall level

Code
total_p_ym=df.groupby(['YearMonth']).agg({'Price':'mean','Quantity':'sum'}).reset_index()
fig = px.scatter(total_p_ym, x='Quantity', y="Price")
fig.update_layout(title_text='Price vs Quantity for All Category', title_x=0.5)
fig.show()

Category Level

Code
print ('Total quantiy sold:',df.Quantity.sum())
Total quantiy sold: 196173

All cateogries are contributing to ~15% of the total sales

Code
cat_sales=df.groupby(['Category'])['Quantity'].agg(sum).reset_index().sort_values(by='Quantity',ascending=False)
fig = px.pie(cat_sales, values='Quantity', names='Category')
fig.update_traces(textinfo='value+percent')
fig.show()

Category sales wrt year month

Oil and Masala has reduced in 2018
Q4 is performing better than rest of the quarters for all categories
Fruits & Veggies sales reduced from 2016 to 2017

Code
cat_q_ym=df.groupby(['Category','YearMonth', 'Month'])['Quantity'].agg(sum).reset_index()
fig = px.line(cat_q_ym, x='YearMonth', y="Quantity", color='Category', facet_col="Category",facet_col_wrap=4)
fig.show()

Include Trend and Seasonal indicator

Trend is added by assigning 1 to first date and then incrementing it by 1
Seasonality is added by including month number

Code
trend_df=df.groupby(['YearMonth','Month'])['Quantity'].agg(sum).reset_index()
trend_df['Trend']=pd.Series(range(1,trend_df.shape[0]+1))
trend_df[['YearMonth','Month','Trend']].head(15)
YearMonth Month Trend
0 2015-01 1 1
1 2015-02 2 2
2 2015-03 3 3
3 2015-04 4 4
4 2015-05 5 5
5 2015-06 6 6
6 2015-07 7 7
7 2015-08 8 8
8 2015-09 9 9
9 2015-10 10 10
10 2015-11 11 11
11 2015-12 12 12
12 2016-01 1 13
13 2016-02 2 14
14 2016-03 3 15

Correlation plot

  • Snacks, Bakery and Food Grains are highly correlated
  • Fruit & Veggies is highly correlated with Egg, Meat & Fish
  • Trend component is around 0.5 for all the categories
  • Seasonal component is correlated more with the category compared to trend component
Code
cat_q_ym
cat_ym_q_pivot=pd.pivot_table(cat_q_ym, values ='Quantity', index =['YearMonth','Month'], columns =['Category'], aggfunc = np.sum).reset_index()
cat_sales_ym=df.groupby(['YearMonth'])['Quantity'].agg(sum).reset_index()
cat_ym_q_pivot=pd.merge(cat_ym_q_pivot, cat_sales_ym, on='YearMonth', how='left')
cat_ym_q_pivot['Trend']=pd.Series(range(1,cat_ym_q_pivot.shape[0]+1))

corr_plot=np.round(cat_ym_q_pivot.corr(),2)
mask=np.triu(np.ones_like(corr_plot, dtype=bool))
f, ax = plt.subplots(figsize=(11, 9))
sns.heatmap(corr_plot,mask=mask, 
#             cmap='PiYG',
            cmap='Greens',
            vmax=1, 
            vmin = 0.4,
            annot = True)
plt.title('Correlation Plot')
plt.show()

Price vs Quantity

At category level there is no significant trend is observed. Slope of the line is close to 0

Code
total_p_ym=df.groupby(['Category','YearMonth']).agg({'Price':'mean','Quantity':'sum'}).reset_index()
# fig = px.scatter(total_p_ym[total_p_ym['Category']=='Beverages'], x='Quantity', y="Price")
fig = px.scatter(total_p_ym, x='Quantity', y="Price", color='Category' , trendline="ols")
fig.update_layout(title_text='Price vs Quantity for Category', title_x=0.5)
fig.show()

Regression Analysis

Category Sales wrt to Sub Category Prices

Equation: \(Category Demand = const+coef_1*Price_{subcat1}+coef_2*Price_{subcat2}+coef_3*Price_{subcat3}+...\)

Code
def coefplot(results, Category_name):
    '''
    Takes in results of OLS model and returns a plot of 
    the coefficients with 95% confidence intervals.
    
    Removes intercept, so if uncentered will return error.
    '''
    # Create dataframe of results summary 
    coef_df = pd.DataFrame(results.summary().tables[1].data)
    
    # Add column names
    coef_df.columns = coef_df.iloc[0]

    # Drop the extra row with column labels
    coef_df=coef_df.drop(0)

    # Set index to variable names 
    coef_df = coef_df.set_index(coef_df.columns[0])

    # Change datatype from object to float
    coef_df = coef_df.astype(float)

    # Get errors; (coef - lower bound of conf interval)
    errors = coef_df['coef'] - coef_df['[0.025']
    
    # Append errors column to dataframe
    coef_df['errors'] = errors

    # Drop the constant for plotting
    coef_df = coef_df.drop(['const'])

    # Sort values by coef ascending
    coef_df = coef_df.sort_values(by=['coef'])

    ### Plot Coefficients ###

    # x-labels
    variables = list(coef_df.index.values)
    
    # Add variables column to dataframe
    coef_df['variables'] = variables
    
    # Set sns plot style back to 'poster'
    # This will make bars wide on plot
    sns.set_context("poster")

    # Define figure, axes, and plot
    fig, ax = plt.subplots(figsize=(10, 3))
    
    # Error bars for 95% confidence interval
    # Can increase capsize to add whiskers
    coef_df.plot(x='variables', y='coef', kind='bar',
                 ax=ax, color='none', fontsize=10, 
                 ecolor='steelblue',capsize=0,
                 yerr='errors', legend=False)
    
    # Set title & labels
    plt.title(Category_name,fontsize=12)
    ax.set_ylabel('Coefficients',fontsize=10)
    ax.set_xlabel('',fontsize=10)
    
    # Coefficients
    ax.scatter(x=pd.np.arange(coef_df.shape[0]), 
               marker='o', s=80, 
               y=coef_df['coef'], color='steelblue')
    
    # Line to define zero on the y-axis
    ax.axhline(y=0, linestyle='--', color='red', linewidth=1)
    
    return plt.show()

Coefficient Regression Plots for all the models

Code
Category_ls=['Bakery', 'Beverages', 'Eggs, Meat & Fish', 'Food Grains', 'Fruits & Veggies', 'Oil & Masala', 'Snacks']

output=pd.DataFrame()

# df_train=df[df['YearMonth']<'2018-09']
df_train=df

subcat_ym=df_train.groupby(['Category','Sub Category','YearMonth','Month']).agg({'Quantity':'sum','Price':'mean'}).reset_index()
cat_ym=df_train.groupby(['Category','YearMonth']).agg({'Quantity':'sum'}).reset_index()
cat_subcat_mapping=pd.DataFrame(df[['Category','Sub Category']].value_counts()).reset_index()
cat_subcat_mapping=cat_subcat_mapping[['Category','Sub Category']]


for cat in Category_ls:
    
#     print(cat)
    temp=pd.DataFrame()
    subcat_ls=cat_subcat_mapping[cat_subcat_mapping['Category']==cat]['Sub Category'].tolist()
    
    subcat_p_ym_pivot=pd.pivot_table(subcat_ym[subcat_ym['Category']==cat], values ='Price', index =['YearMonth','Month'], columns =['Sub Category'], aggfunc = np.sum).reset_index()
    subcat_p_ym_pivot['Trend']=pd.Series(range(1,subcat_p_ym_pivot.shape[0]+1))
    qty_ym=cat_ym[cat_ym['Category']==cat][['YearMonth','Quantity']]
    
#     print(subcat_p_ym_pivot)
    price_model_cat=pd.merge(subcat_p_ym_pivot,qty_ym,on='YearMonth',how='left')
    price_model_cat=price_model_cat.fillna(price_model_cat.rolling(3, min_periods=1).mean().shift())
#     print(price_model_cat)
    price_model_cat_X = sm.add_constant(price_model_cat[['Month','Trend']+subcat_ls], prepend=False)
    mod = sm.OLS(price_model_cat.Quantity, price_model_cat_X)
    res = mod.fit()
#     print(res.summary())
    coefplot(res, cat)
    temp['Variable']=res.model.exog_names
    temp['Coefficient']=res.params.values
    temp['Category']=cat 
    
    output=output.append(temp, ignore_index=True)
#     print(output)

Code
output_coeff=output[['Category','Variable','Coefficient']].sort_values(by=['Category','Coefficient'], ascending=True)
# .style.background_gradient(cmap='RdGy')
# output_coeff

Regression coeficient values in tabular format

Code
df1_styler = output_coeff[output_coeff['Category']=='Bakery'][['Variable','Coefficient']].reset_index(drop=True).style.background_gradient(cmap='RdGy').set_table_attributes("style='display:inline'").set_caption('Bakery')
df2_styler = output_coeff[output_coeff['Category']=='Beverages'][['Variable','Coefficient']].reset_index(drop=True).style.background_gradient(cmap='RdGy').set_table_attributes("style='display:inline'").set_caption('Beverages')
df3_styler = output_coeff[output_coeff['Category']=='Eggs, Meat & Fish'][['Variable','Coefficient']].reset_index(drop=True).style.background_gradient(cmap='RdGy').set_table_attributes("style='display:inline'").set_caption('Eggs, Meat & Fish')
df4_styler = output_coeff[output_coeff['Category']=='Food Grains'][['Variable','Coefficient']].reset_index(drop=True).style.background_gradient(cmap='RdGy').set_table_attributes("style='display:inline'").set_caption('Food Grains')
df5_styler = output_coeff[output_coeff['Category']=='Fruits & Veggies'][['Variable','Coefficient']].reset_index(drop=True).style.background_gradient(cmap='RdGy').set_table_attributes("style='display:inline'").set_caption('Fruits & Veggies')
df6_styler = output_coeff[output_coeff['Category']=='Oil & Masala'][['Variable','Coefficient']].reset_index(drop=True).style.background_gradient(cmap='RdGy').set_table_attributes("style='display:inline'").set_caption('Oil & Masala')
df7_styler = output_coeff[output_coeff['Category']=='Snacks'][['Variable','Coefficient']].reset_index(drop=True).style.background_gradient(cmap='RdGy').set_table_attributes("style='display:inline'").set_caption('Snacks')


space = "\xa0" * 10
display_html(df1_styler._repr_html_()+space+df2_styler._repr_html_()+space+df3_styler._repr_html_()+space+df4_styler._repr_html_()+space+df5_styler._repr_html_()+space+df6_styler._repr_html_()+space+df7_styler._repr_html_(), raw=True)
# display_html(df5_styler._repr_html_()+space+df6_styler._repr_html_()+space+df7_styler._repr_html_(), raw=True)
Bakery
  Variable Coefficient
0 Breads & Buns -1.086242
1 Cakes -0.251251
2 Biscuits -0.082141
3 Trend 8.894311
4 Month 65.746638
5 const 140.539283
          
Beverages
  Variable Coefficient
0 Health Drinks -0.965430
1 Soft Drinks -0.290544
2 Trend 8.381029
3 Month 46.494121
4 const 250.300922
          
Eggs, Meat & Fish
  Variable Coefficient
0 Eggs -0.706483
1 Chicken -0.554023
2 Mutton -0.117788
3 Fish 0.049169
4 Trend 11.065731
5 Month 60.206332
6 const 130.620098
          
Food Grains
  Variable Coefficient
0 Organic Staples -0.429108
1 Rice -0.181652
2 Dals & Pulses -0.065190
3 Atta & Flour 0.093873
4 Trend 10.595552
5 const 26.955690
6 Month 57.703610
          
Fruits & Veggies
  Variable Coefficient
0 const -9.137286
1 Fresh Vegetables -0.223045
2 Fresh Fruits -0.125664
3 Organic Fruits -0.112682
4 Organic Vegetables 0.460909
5 Trend 8.570907
6 Month 60.829556
          
Oil & Masala
  Variable Coefficient
0 Masalas -0.727665
1 Spices -0.120953
2 Edible Oil & Ghee 0.280271
3 Trend 8.577789
4 Month 47.300495
5 const 128.184998
          
Snacks
  Variable Coefficient
0 Chocolates -0.889797
1 Noodles -0.763125
2 Cookies -0.062719
3 Trend 12.724632
4 Month 56.185318
5 const 230.839103

Prediction

Code
pred_df[['Category','YearMonth','Actual','Predicted']]
Category YearMonth Actual Predicted
0 Bakery 2018-09 1176 793.884786
1 Bakery 2018-10 948 907.289841
2 Bakery 2018-11 1336 1025.692555
3 Bakery 2018-12 1144 987.300701
4 Beverages 2018-09 1064 764.340078
5 Beverages 2018-10 749 737.847580
6 Beverages 2018-11 1203 866.662852
7 Beverages 2018-12 1415 856.015880
8 Eggs, Meat & Fish 2018-09 1699 880.098797
9 Eggs, Meat & Fish 2018-10 697 942.236007
10 Eggs, Meat & Fish 2018-11 1029 1007.953825
11 Eggs, Meat & Fish 2018-12 1430 1052.338362
12 Food Grains 2018-09 1316 859.628290
13 Food Grains 2018-10 865 1004.396308
14 Food Grains 2018-11 1348 898.473128
15 Food Grains 2018-12 1052 1086.605885
16 Fruits & Veggies 2018-09 1237 807.159613
17 Fruits & Veggies 2018-10 849 896.061309
18 Fruits & Veggies 2018-11 1163 952.495670
19 Fruits & Veggies 2018-12 1501 1090.346768
20 Oil & Masala 2018-09 1023 823.730382
21 Oil & Masala 2018-10 798 885.632846
22 Oil & Masala 2018-11 1232 925.337395
23 Oil & Masala 2018-12 1205 986.035445
24 Snacks 2018-09 1478 931.136825
25 Snacks 2018-10 724 894.805078
26 Snacks 2018-11 1832 1108.481441
27 Snacks 2018-12 1276 1090.186614

Category level MAPE

Equation: \(MAPE = mean(abs((actual-predicted)/actual))\)

Code
pred_df.groupby(['Category']).MAPE.mean().reset_index().sort_values('MAPE')
Category MAPE
5 Oil & Masala 18.380821
0 Bakery 18.427802
4 Fruits & Veggies 21.437630
3 Food Grains 21.857776
1 Beverages 24.278720
2 Eggs, Meat & Fish 27.959681
6 Snacks 28.661906

Sub Category Demand wrt to its Price

Equation: \(Subcat Demand = Coef * Price + constant\)

Code
Category_ls=['Bakery', 'Beverages', 'Eggs, Meat & Fish', 'Food Grains', 'Fruits & Veggies', 'Oil & Masala', 'Snacks']

output=pd.DataFrame()

# df_train=df[df['YearMonth']<'2018-09']
df_train=df

subcat_ym=df_train.groupby(['Category','Sub Category','YearMonth','Month']).agg({'Quantity':'sum','Price':'mean'}).reset_index()
cat_ym=df_train.groupby(['Category','YearMonth']).agg({'Quantity':'sum'}).reset_index()
cat_subcat_mapping=pd.DataFrame(df[['Category','Sub Category']].value_counts()).reset_index()
cat_subcat_mapping=cat_subcat_mapping[['Category','Sub Category']]


for cat in Category_ls:
    
#     print(cat)
    
    subcat_ls=cat_subcat_mapping[cat_subcat_mapping['Category']==cat]['Sub Category'].tolist()
    
    for subcat in subcat_ls:
#         print(subcat)
        temp=pd.DataFrame()
        subcat_p_ym_t=subcat_ym[subcat_ym['Sub Category']==subcat]
#         print(subcat_p_ym_t)
            
        subcat_p_ym_t['Trend']=pd.Series(range(1,subcat_p_ym_t.shape[0]+1)).values
    
        subcat_p_ym_t=subcat_p_ym_t.fillna(subcat_p_ym_t.rolling(3, min_periods=1).mean().shift())
        subcat_p_ym_t_X = sm.add_constant(subcat_p_ym_t[['Price','Month','Trend']], prepend=False)
        mod = sm.OLS(subcat_p_ym_t.Quantity, subcat_p_ym_t_X)
        res = mod.fit()
#         print(res.summary())
    
        temp['Variable']=res.model.exog_names
        temp['Coefficient']=res.params.values
        temp['Category']=cat 
        temp['Sub Category']=subcat
        output=output.append(temp, ignore_index=True)
#     print(output)
Code
output[output['Variable']=='Price'][['Category','Sub Category','Variable','Coefficient']].sort_values(by='Coefficient', ascending=True).style.background_gradient(cmap='RdYlGn')
  Category Sub Category Variable Coefficient
80 Snacks Cookies Price -0.674563
0 Bakery Breads & Buns Price -0.633320
88 Snacks Noodles Price -0.556082
68 Oil & Masala Masalas Price -0.488256
12 Beverages Health Drinks Price -0.402775
84 Snacks Chocolates Price -0.383040
24 Eggs, Meat & Fish Eggs Price -0.345920
20 Eggs, Meat & Fish Mutton Price -0.319583
64 Fruits & Veggies Organic Vegetables Price -0.298968
36 Food Grains Organic Staples Price -0.293816
44 Food Grains Dals & Pulses Price -0.202027
8 Bakery Cakes Price -0.196595
16 Beverages Soft Drinks Price -0.178806
32 Eggs, Meat & Fish Chicken Price -0.164009
56 Fruits & Veggies Fresh Vegetables Price -0.157494
76 Oil & Masala Spices Price -0.097857
60 Fruits & Veggies Organic Fruits Price -0.092019
52 Fruits & Veggies Fresh Fruits Price -0.083300
28 Eggs, Meat & Fish Fish Price -0.074796
48 Food Grains Rice Price -0.062922
40 Food Grains Atta & Flour Price -0.034715
72 Oil & Masala Edible Oil & Ghee Price 0.020378
4 Bakery Biscuits Price 0.025511
Code
import nbdev; nbdev.nbdev_export()